package com.yvon.maple.service.msg.sub.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Sets;
import com.yvon.maple.cloud.api.system.feign.UserFeignClient;
import com.yvon.maple.service.msg.core.common.enums.BusinessCode;
import com.yvon.maple.service.msg.core.model.vo.MessageVo;
import com.yvon.maple.service.msg.core.model.vo.SendDTO;
import com.yvon.maple.service.msg.core.model.vo.SendParam;
import com.yvon.maple.service.msg.core.service.SendService;
import com.yvon.maple.service.msg.sub.model.entity.SubscribeActive;
import com.yvon.maple.service.msg.sub.model.entity.SubscribePassive;
import com.yvon.maple.service.msg.sub.model.entity.SubscribeTemplate;
import com.yvon.maple.service.msg.sub.model.vo.SubscribeVo;
import com.yvon.maple.service.msg.sub.service.SubscribeActiveService;
import com.yvon.maple.service.msg.sub.service.SubscribePassiveService;
import com.yvon.maple.service.msg.sub.service.SubscribeTemplateService;
import com.yvon.maple.service.msg.sub.service.SubscribeSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author : Yvon
 * @since : 2021-12-30
 */
@Service
@Slf4j
public class SubscribeSendServiceImpl implements SubscribeSendService {

    @Autowired
    private SubscribeTemplateService templateService;

    @Resource
    private SubscribePassiveService passiveService;

    @Resource
    private SubscribeActiveService activeService;

    @Autowired
    private SendService sendService;

    @Autowired
    private UserFeignClient userFeignClient;



    private SendDTO coreSend(String templateId, Set<String> receiver, Map<String, String> vars) {
        SendParam sendParam = new SendParam();
        sendParam.setMessageTemplateId(Long.parseLong(templateId));
        MessageVo messageVo = new MessageVo();
        messageVo.setReceiver(receiver);
        messageVo.setVariables(vars);
        sendParam.setCode(BusinessCode.COMMON_SEND.getCode());
        sendParam.setMessageVo(messageVo);
        return sendService.send(sendParam);
    }

    @Override
    public boolean sendMsg(SubscribeVo subscribeVo) {
        subscribeVo.getSubscribeIds().forEach(subscribeId -> {
            SubscribeTemplate subscribeTemplate = templateService.getById(subscribeId);
            if (Objects.isNull(subscribeTemplate)) {
                log.warn("订阅模板不存在：{}", subscribeId);
                return;
            }
            if (subscribeTemplate.getType() == 0) {
                SubscribeActive subscribeActive = activeService.getBySubscribeId(subscribeId);
                if (Objects.nonNull(subscribeActive)) {
                    Map<String, String> channelTemplate = subscribeActive.getChannelTemplate();
                    Set<String> keySet = channelTemplate.keySet();

                    keySet.forEach(key -> {
                        Set<String> receiver;
                        if (CollUtil.isNotEmpty(subscribeVo.getReceivers())) {
                            receiver = Sets.newHashSet(subscribeVo.getReceivers());
                        }else {
                            receiver = userFeignClient.getReceiverByUserIds(Sets.newHashSet(String.valueOf(subscribeActive.getUserId())), key);
                        }
                        SendDTO sendDTO = coreSend(channelTemplate.get(key), receiver, subscribeVo.getVars());
                        log.info("【{}】发送结果: {}",key, sendDTO.getMsg());
                    });
                }
            }else {
                SubscribePassive subscribePassive = passiveService.getBySubscribeId(subscribeId);
                if (Objects.nonNull(subscribePassive)) {
                    Map<String, String> channelTemplate = subscribePassive.getChannelTemplate();
                    Set<String> keySet = channelTemplate.keySet();

                    keySet.forEach(key -> {
                        Set<String> receiver;
                        if (CollUtil.isNotEmpty(subscribeVo.getReceivers())) {
                            receiver = Sets.newHashSet(subscribeVo.getReceivers());
                        }else {
                            receiver = new HashSet<>();
                            if (CollUtil.isNotEmpty(subscribePassive.getUsers())) {
                                receiver.addAll(userFeignClient.getReceiverByUserIds(subscribePassive.getUsers().keySet(), key));
                            }
                            if (CollUtil.isNotEmpty(subscribePassive.getRoles())) {
                                receiver.addAll(userFeignClient.getReceiverByRoles(subscribePassive.getRoles().keySet(), key));
                            }
                        }
                        SendDTO sendDTO = coreSend(channelTemplate.get(key), receiver, subscribeVo.getVars());
                        log.info("【{}】发送结果: {}", key, sendDTO.getMsg());
                    });
                }
            }
        });

        return true;

    }
}
